﻿package com.gobang.netmode.search;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import com.gobang.gobangui.MainWindowUI;
import com.gobang.netmode.clientdata.ChessClient;
import com.gobang.netmode.sendandreceive.Message;
import com.gobang.netmode.sendandreceive.MessageMSG;
import com.gobang.netmode.sendandreceive.Order;
import com.gobang.netmode.sendandreceive.SendAndReceive;
import com.gobang.netmode.util.ClientDataClass;
import com.gobang.netmode.util.Netmode;
import com.gobang.netmode.util.ServerMessage;

public class SearchOfVisitor extends Thread {
	/*
	 * 打开房间之后自动连上服务器,每十秒自动刷新，或者点击刷新后马上刷新，
	 * 如果掉线之后点击刷新会主动重新连接服务器，
	 * 直到搜索房间的界面被隐藏之后结束线程
	 */
	SearchJFrameOfWAN searchJFrameOfWAN;
	SendAndReceive sendAndReceive;
	boolean isWork = false;
	boolean isRun = false;
	Message message = new Message();
	ClientDataClass client;
	Socket socket;
	
	public SearchOfVisitor(SearchJFrameOfWAN s, ClientDataClass client) {
		// TODO Auto-generated constructor stub
		searchJFrameOfWAN = s;
		this.client = client;
	}
	@Override
	public void run() {
		isRun = true;
		// TODO Auto-generated method stub
		while(isRun && searchJFrameOfWAN.isVisible() && MainWindowUI.getNetmode() == Netmode.WAN){
			try {
				if(!isWork){//尝试建立与主服务器的连接
					System.out.println("SearchOfVisitor.run()尝试与服务器链接！");
				socket = new Socket(SearchJFrameOfWAN.ServerDomain, SearchJFrameOfWAN.portOfWAN);//测试阶段
				searchJFrameOfWAN.getProgressThread().setConnect(true);
				System.out.println("SearchOfVisitor.run()与服务器链接成功"+socket);
				sendAndReceive = new SendAndReceive(socket);
				isWork = true;
					new Thread() {//当连接成功后马上建立新的线程来时时接收并处理主服务器的信息
						public void run() {
							while (isWork && isRun && MainWindowUI.getNetmode() == Netmode.WAN && ((SearchJFrameOfWAN)MainWindowUI.getSearchframe()).isVisible() ) {
								try {
									searchJFrameOfWAN.getProgressThread().setSend(true);
									message = sendAndReceive.receiveMessage();// 接收信息
									if (message != null) {
										searchJFrameOfWAN.getProgressThread().setReceive(true);
										System.out.println("SearchOfVisitor.run()" + message.toString());
										operation(message);
									} else {
										isWork = false;
									}
								} catch (ClassNotFoundException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									isWork = false;
								}
							}
						}
					}.start();
				}  //**************if(!isWork)尝试建立与主服务器的连接    end
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				isWork = false;
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				isWork = false;
				e.printStackTrace();
			}
			while(isWork && ((SearchJFrameOfWAN)MainWindowUI.getSearchframe()).isVisible() ){//每隔十秒自动发送一次消息
				isWork = sendAskRoomMessage();
				if(isWork){
					searchJFrameOfWAN.getProgressThread().setSend(true);
				}
				try {
					Thread.sleep(60000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		isWork = false;
	}
	private synchronized void operation(Message message){
		ChessClient chessClient;
		switch (message.order) {
//		case CREATE_ROOM:
//			//建立房间成功，根据此信息可以连接上刚创建好的房间
//			if(message.serverMessageVector != null){
//				((SearchJFrameOfWAN)MainWindowUI.getSearchframe()).connectServerOfRoom(message.serverMessageVector.get(0));
//			}else{
//				System.out.println("SearchOfVisitor.operation()创建房间失败！"+client);
//			}
//			
//			break;
		case JOIN:
		   chessClient = new ChessClient(( (SearchJFrameOfWAN)MainWindowUI.getSearchframe()).getNameString(), MainWindowUI.getID(), sendAndReceive);
			isWork = false;
			((SearchJFrameOfWAN)MainWindowUI.getSearchframe()).setVisible(false);
			break;
		case JOIN_FAIL:
		    break;
		case CREATE_ROOM_SUCCESS:
			if(!((SearchJFrameOfWAN)MainWindowUI.getSearchframe()).getNameString().equals("")){
				 chessClient = new ChessClient(( (SearchJFrameOfWAN)MainWindowUI.getSearchframe()).getNameString(), MainWindowUI.getID(), sendAndReceive);
				 isWork = false;
				((SearchJFrameOfWAN)MainWindowUI.getSearchframe()).setVisible(false);
			}
			break;
		case CREATE_ROOM_FAIL://创建失败
			System.out.println("SearchOfVisitor.operation()广域网房间创建失败!");
			break;
		case ALL_ROOMMSG:
			//显示所有房间的信息
			SearchJFrameOfWAN.serverMessageVector = message.serverMessageVector;
			new Thread(){
				public void run() 
				{
					SearchJFrameOfWAN.showServer();
				};
			}.start();
			break;
		case NULL:
			if((message.msg & MessageMSG.SERVER_MESSAGE_VECTOR) == MessageMSG.SERVER_MESSAGE_VECTOR ){
				System.out.println("SearchOfVisitor.operation()服务器没有房间，请用户自己建立房间");
			}
		default:
			break;
		}
	}
	
	public synchronized boolean sendCreateRoom(ClientDataClass client){
		Message message = new Message();
		if(! isWork){
		return false;
		}else  if(sendAndReceive != null){
			client.setClientAddress(socket.getLocalAddress()); 
			message.clientDataClass = client;
			message.order = Order.CREATE_ROOM;
			message.msg = MessageMSG.CLIENT_DATA_CLASS + MessageMSG.ORDER;
			if(sendAndReceive.sendMessage(message)){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

	public synchronized boolean sendAskRoomMessage() {
		Message message = new Message();
		if (!isWork) {
			return false;
		}else if (sendAndReceive != null) {
			message.clientDataClass = client;
			message.order = Order.ASK_ROOMMSG;
			message.msg = MessageMSG.CLIENT_DATA_CLASS + MessageMSG.ORDER;
			if (sendAndReceive.sendMessage(message)) {
				return true;
			}else {
				return false;
			}
		}else {
			return false;
		}
	}
	public synchronized boolean sendJoinRoom(ServerMessage serverMessage, ClientDataClass client){
		Message message = new Message();
		if(! isWork){
		return false;
		}else  if(sendAndReceive != null){
			message.clientDataClass = client;
			message.order = Order.JOIN;
			message.serverMessage = serverMessage;
			message.msg = MessageMSG.CLIENT_DATA_CLASS + MessageMSG.ORDER + MessageMSG.SERVER_MESSAGE;
			if(sendAndReceive.sendMessage(message)){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

}
